<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/2
 * Time: 13:17
 */

namespace app\admin\controller;
use app\admin\model\Party;
use app\admin\model\Regulation;
use app\admin\model\Country;
use com\wechat\TPWechat;
use app\admin\model\Push as PushModel;
use app\home\model\Picture;
use think\Config;
/**消息推送控制器
 * Class push
 * @package app\admin\controller
 */
class Push extends Admin
{
    /*
     * 已推送文章页
     */
    public function index(){
        //查询可推荐的文章
        if (IS_POST){
            //副图文
            $id = input('id');
            $type = strtolower(input('type'));
            $map1 = [
                    'status'=>0,
                    'push'=>1,
            ];
            $map2 = [
                'id'=>['neq',$id],
                'status'=>0,
                'push'=>1,
            ];
            $regulation =Regulation::where($map1)->field('id,title')->select();
            $party = Party::where($map1)->field('id,title')->select();
            $country = Country::where($map1)->field('id,title')->select();
            switch ($type){
                case 'regulation':
                    $regulation =Regulation::where($map2)->field('id,title')->select();
                    break;
                case 'party':
                    $party = Party::where($map2)->field('id,title')->select();
                    break;
                case 'country':
                    $country = Party::where($map2)->field('id,title')->select();
                    break;
                default:
                    break;
            }
            $res = [
                'regulation'=>$regulation,
                'party'=>$party,
                'country'=>$country
            ];
            return $this->success($res);
        }else{
            //消息列表
            $map1=[
                'status'=>1,
            ];
            $list = $this->lists('Push',$map1);
            int_to_string($list, array(
                'status'=>[1=>'已推送'],
            ));
            $info = [];
            foreach ($list as $value){
                $res = $this->getPush($value['table'],$value['a_id']);
                $value['title'] = $res['title'];
                $info[] = $value;
            }
            $map2 = [
                'status'=>0,
                'push'=>1,
            ];
            $regulation = Regulation::where($map2)->field('id,title')->select();
            $party = Party::where($map2)->field('id,title')->select();
            $country =Country::where($map2)->field('id,title')->select();
            $this->assign([
                'info'=>$info,
                'regulation'=>$regulation,
                'party'=>$party,
                'country'=>$country,
                'list'=>'',
            ]);
            return $this->fetch();
        }
    }

    /**
     * 文章推送
     */
    public function push(){
        $data = input('post.');
        if ($data['focus_main'] == -1){
            return $this->error('未选择主图文');
        }
        if (!empty($data['focus_vice'])){
            $main = [[
                'id'=>$data['focus_main'],
                'type'=>$data['main_type'],
                ]];
            $len = count($data['focus_vice'])-1;
            for ($i = 0;$i<=$len;$i++){
                $vice[] = ['id'=>$data['focus_vice'][$i],'type'=>$data['vice_type'][$i]];
            }
            foreach ($vice as $value){
                $main[] = $value;
            }
        }else{
            $main = [[
                'id'=>$data['focus_main'],
                'type'=>$data['main_type'],
            ]];
        }
        $news_id = $this->getSendMessage($main);
        $array = [
//            "touser"=>"oyANe1q_vL0dVaKeOJsppTwRErkg",
            "filter"=>array(
                "is_to_all"=>true,
                ),
            "msgtype"=>"mpnews",
            "mpnews"=>["media_id"=>$news_id],
//            "send_ignore_reprint"=>0,
        ];
        $weChat = new TPWechat(Config::get('party'));
        $pushModel = new PushModel();
        $res = $weChat->sendGroupMassMessage($array);
        if ($res['errcode'] == 0){
                $item = $main[0];
                $info['a_id'] = $item['id'];
                $info['table'] = $item['type'];
                $info['push_time'] = NOW_TIME;
                $info['create_user'] = $_SESSION['think']['user_auth']['id'];
                $res = $pushModel->save($info);
        }else{
            $res = false;
        }
        if ($res){
            return $this->success('发布成功');
        }else{
            return$this->error('发布失败');
        }
    }

    /*
     * 获取推送文章
     */
    private function getPush($type,$id){
        switch ($type){
            case 'regulation':
                $Model = new Regulation();
                break;
            case 'party':
                $Model = new Party();
                break;
            case 'country':
                $Model = new Country();
                break;
            default:
                break;
        }
        $map = [
            'id'=>$id,
            'status'=>0
        ];
       return $Model->where($map)->find();
    }

    /*
     上传图文消息
    */
    public function getSendMessage($main){
        $weChat = new TPWechat(Config::get('party'));
        foreach ($main as $value){
            $list = $this->getPush($value['type'],$value['id']);
            $title = $list['title'];
            $content = $list['content'];
            switch ($value['type']){
                case 'regulation':
                    $url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] . "/home/regulation/detail/id/" . $list['id'] . ".html";
                    break;
                case 'party':
                    $url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] . "/home/party/detail/id/" . $list['id'] . ".html";
                    break;
                case 'country':
                    $url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] . "/home/Country/detail/id/" . $list['id'] . ".html";
                    break;
                default:
                    break;
            }
            $img = $this->roundPic();
//            $img = '/uploads/download/2018-03-27/5ab9da348b3e5.jpg';
            $data =array('media'=>'@.'.$img) ;
            $pic = $weChat->uploadForeverMedia($data,'thumb');
            $info = array(
                'thumb_media_id'=>$pic['media_id'],
                "title" => $title,
                'content_source_url'=>$url,
                'content'=>$content,
                'show_cover_pic'=>0,
            );
            $send['articles'][] = $info;

        }
        $news = $weChat->uploadForeverArticles($send);
        return $news['media_id'];
    }

    /*
     * 随机封面图片
     * */
    public function roundPic()
    {
        $pic = \app\admin\model\Picture::where('status','egt',0)->limit(4,14)->field('path')->select();
        $picPath = [];
        foreach ($pic as $value){
            $picPath[] = $value['path'];
        }
       $key =array_rand($picPath,1);
        return $picPath[$key];
    }
}